

<?php
error_reporting(E_ALL);

if (isset($_POST['action']) && ($_POST['action'] == 'multiple')) {
session_start(); // Start session first thing in script/////////////////////////////////////
error_reporting(E_ALL);
include_once('controller/includes/db_access.php');

//die('datum'.$_POST['dt']);
// kijk of datum geselecteerd is vanaf stap1////////////////////////////////////
  if(isset($_POST['dt']) && ($_POST['dt'] == 'dt') ){           
    function dateformat($param) {
    // format "2012-06-19"  
    $dt = strftime("%Y-%m-%d", strtotime($param));
    // convertir les accents (pour encodage UTF-8)////////////////////////////////////////  
    $dt = mb_convert_encoding($dt, 'utf-8');
    return $dt;
    }

    //1 post datum from stap1
   if ($_POST['van']!='') $_SESSION['van'] = $_POST['van'];
   if ($_POST['tot']!='')$_SESSION['tot'] = $_POST['tot'];
    $van_datum = dateformat($_SESSION['van']);
    $tot_datum = dateformat($_SESSION['tot']);


    //1.1 count aantal dagen
    function daysDifference($endDate, $beginDate) 

    {
    //explode the date by "-" and storing to array
    $date_parts1 = explode("-", $beginDate);
    $date_parts2 = explode("-", $endDate);
    //gregoriantojd() Converts a Gregorian date to Julian Day Count
    $start_date = gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
    $end_date = gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
    return $end_date - $start_date;
    }


    $total_day = daysDifference($tot_datum, $van_datum);
    
    if($total_day <= 0) $total_day = 1;
    
    // function random bestellingsnummer
    function randomBestellingsnummer() {

        static $characters = 'abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVW';

        return str_shuffle($characters);
    }

    function transforme_HTML($chaine, $longueur = null) {
// Aide à empêcher les attaques XSS
// Supression des espaces inutiles.
        $chaine = trim($chaine);
// Empêche des problèmes potentiels avec le codec Unicode.
        $chaine = utf8_decode($chaine);
// HTMLise les caractères spécifiques à HTML.
        $chaine = htmlentities($chaine, ENT_NOQUOTES);
        $chaine = str_replace("#", "&#35;", $chaine);
        $chaine = str_replace("%", "&#37;", $chaine);
        $longueur = intval($longueur);
        if ($longueur > 0) {

            $chaine = substr($chaine, 0, $longueur);
        }
        return $chaine;
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //                                    KLANTEN                                                                   //
    // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    $bedrijfsnaam = transforme_HTML($_POST['bedrijfsnaam']);
    $contactnaam = transforme_HTML($_POST['contactnaam']);
    $straat = transforme_HTML($_POST['straat']);
    $postcode = transforme_HTML($_POST['postcode']);
    $plaats = transforme_HTML($_POST['plaats']);
    $tel = transforme_HTML($_POST['tel']);
    $email = transforme_HTML($_POST['email']);
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //                                  EVENT LOCATIE                                                               //
    // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
    $aanvangstijd = transforme_HTML($_POST['aanvangstijd']);
    $contactnaam2 = transforme_HTML($_POST['contactnaam2']);
    $straat2 = transforme_HTML($_POST['straat2']);
    $postcode2 = transforme_HTML($_POST['postcode2']);
    $plaats2 = transforme_HTML($_POST['plaats2']);
    $tel2 = transforme_HTML($_POST['tel2']);
    $naam_cont_loc = transforme_HTML($_POST['naam_cont_loc']);

    $verzendmethode = transforme_HTML($_POST['hb']);


    $klant_query = mysql_query("INSERT INTO  `dbme_nl_servan`.`klanten` (`name` , `bedrijfnaam` , `straat` , `postcode` , `plaats` , `tel_nr` , `email` , `crea_datum`) VALUES ('$bedrijfsnaam',  '$contactnaam',  '$straat',  '$postcode',  '$plaats',  '$tel',  '$email', NOW( ))");
    $klant_id = mysql_insert_id();
    
    if (isset($klant_id) && ($klant_id > 0)) {

        $characters = 0;
        $length = 8;
        $bestellingsnummer = substr($klant_id . '' . randomBestellingsnummer($characters), 0, $length);


        $order_query = mysql_query(" INSERT INTO  `dbme_nl_servan`.`offerte` ( `klant_id` , `offerte_datum` , `verzendmethode` , `offertestatus` , `offertesnummer` )
     VALUES ( $klant_id,  NOW(), '$verzendmethode',  'offerte',  '$bestellingsnummer')");
        $offerte_id = mysql_insert_id();

        if (isset($offerte_id) && ($offerte_id > 0 )) {
                $event_locatie_query = mysql_query("INSERT INTO  `dbme_nl_servan`.`event_loactie` (
                `klant_id` ,
                `offerte_id` ,
                `name` ,
                `aanvangstijd` ,
                `straat` ,
                `postcode` ,
                `plaats` ,
                `tel_nr` ,
                `naam_cont_loc` ,
                `crea_datum`
                )
                VALUES ('$klant_id',  '$offerte_id',  '$contactnaam2',  '$aanvangstijd',  '$straat2',  '$postcode2',  '$plaats2',  '$tel2',  '$naam_cont_loc', NOW( )
                );
                ");
            $event_loactie_id = mysql_insert_id();

            if (isset($event_loactie_id) && ($event_loactie_id > 0 )) {
                //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                                     SET                                                                      //
                // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
                if ($_POST['set_id'] != '')
                    $_SESSION['set_id'] = $_POST['set_id'];
                if (isset($_SESSION['set_id']) > 0) {
                    $SQLSet = "SELECT * FROM sets WHERE set_id=" . $_SESSION['set_id'];
                    $querySet = mysql_query($SQLSet);
                    $rowSet = mysql_fetch_object($querySet);
                    $setprijs = number_format($rowSet->setprijs, 2, '.', ' ');
                    $periode_setprijs = ($setprijs * $total_day);
                    $periode_setprijs = number_format($periode_setprijs, 2, ',', ' ');
                    $setnaam = $rowSet->naam;
                }


                if ($_POST['aantal'] != '')
                    $_SESSION["aantal"] = $_POST['aantal'];
                foreach ($_SESSION["aantal"] as $aantal_per_product) {

                    $aantal .= $aantal_per_product;
                    $aantal_in_sys = array($aantal,);
                }

                //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                                     PRODUCTEN                                                                //
                // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
                $productteller = 0;
                $_SESSION["aantalarray"] = $_SESSION["aantal"];
                $aantalarray = $_SESSION["aantalarray"];
                if ($_POST['product'] != '') $_SESSION["product"] = $_POST['product'];

                foreach ($_POST['product'] as $product_id) {

                    $SQLProd = "SELECT * FROM product WHERE product_id=" . $product_id;
                    $queryProd = mysql_query($SQLProd);
                    $rowPerProd = mysql_fetch_object($queryProd);
                    $dagprijs = ($rowPerProd->huurprijs * $aantalarray[$productteller]);
                    $all_periodePrijs = ($dagprijs * $total_day);
                    $totaal_periodePrijs += $all_periodePrijs;
                    $totaalhuurprijs +=$dagprijs;

                   $orderinhoud_query = mysql_query("INSERT INTO  `dbme_nl_servan`.`offertesinhoud` (`offerte_id` , `product_id` , `aantal` ,  `prijs` , `totalprijs` , `offertedatum` )
                    VALUES ($offerte_id, $product_id, '$aantalarray[$productteller]', '$dagprijs', '$all_periodePrijs', NOW())");

                    $productteller++;
                }


                $dag_subtotaal = ($totaalhuurprijs + $setprijs);
                $periode_subtotaal = ($totaal_periodePrijs + $periode_setprijs);

                $staffelkorting_db = 50; // UIT DB HALEN

                $staffelkorting = $staffelkorting_db / 100; //0.50;

                $teBetalen = (1 * $dag_subtotaal + (($total_day - 1) * ($dag_subtotaal * $staffelkorting)));

                $percentage = ($teBetalen / ($dag_subtotaal * $total_day));

                $percentage = 100 - ($percentage * 100);



                //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                //                             BEGIN DIENST                                                                     //
                // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

                if ($_POST['dienst'] != '')
                    $_SESSION['dienst'] = $_POST['dienst'];
                if (isset($_SESSION['dienst'])) {
                    foreach ($_SESSION['dienst'] as $dienst_id) {
                        $sqlDienst = "SELECT * FROM diensten WHERE dienst_id=" . $dienst_id;
                        $resultDienst = mysql_query($sqlDienst);
                        $rowDienst = mysql_fetch_object($resultDienst);
                        $periodiek_totaal_dienstprijs = $rowDienst->prijs;
                        //$totaal_periode_dienst+= $dienst_prijs;
                        $totaal_periode_dienst_prijs += $rowDienst->prijs;

                        if ($rowDienst->eenxdienst == 'N') {
                            $eenXdienst = $rowDienst->prijss;
                            $totaaldienst_prijs +=$eenXdienst;
                            $totaaldienst = $totaaldienst_prijs * $total_day;
                            $rowDienst->naam;
                        }
                        $totalprijs = $totaal_periode_dienst_prijs + $periodiek_totaal_dienstprijs;
                        $offertesinhoud_dienten_query = mysql_query("INSERT INTO  `dbme_nl_servan`.`offertesinhoud_dienten` (
        `offerte_id` ,
        `dienst_id` ,
        `aantal` ,
        `prijs` ,
        `totalprijs` ,
        `offertedatum`
        )
        VALUES ($offerte_id,  $dienst_id,  '$total_day',  '$periodiek_totaal_dienstprijs',  '$totalprijs', NOW( ))");
                    }
                    $exbtwbedrag = ($totaal_periode_dienst_prijs + $periodiek_totaal_dienstprijs + $teBetalen);
                }



                if (isset($_POST['kcode'])) {

                    $kcode = $_POST['kcode'];

                    $sql_korting = mysql_query("SELECT * FROM cadeaubon WHERE code='$kcode' AND aktief='Y'");
                    $countkorting = mysql_num_rows($sql_korting);
                    $korting = mysql_fetch_array($sql_korting);
                    $type = $korting['type'];
                    $aktie = $korting['korting'];

                    if ($countkorting == 1) {
                        $cadeaubon_id = $korting['cadeaubon_id'];
                        switch ($type) {
                            case $type == 'A':
                                $_SESSION["aktie_korting"] = $aktie;
                                $aktie = $_SESSION["aktie_korting"];
                                $korting_waarde = ($exbtwbedrag * ($aktie / 100));
                                $_SESSION["aktie_waarde"] = $korting_waarde;
                                $korting_waarde = $_SESSION["aktie_waarde"];
                                break; //end case $type=='A'

                            case $type == 'C':

                                $_SESSION["cadeaubon_waarde"] = $korting['korting'];
                                $cadeaubon = $_SESSION["cadeaubon_waarde"];
                                $waarde = $cadeaubon;

                                break; //end case $type=='C'
                        }//end switch $type=='C' or $type=='A'
                    }
                }
                if (isset($_SESSION["aktie_korting"])) {

                    $Subtotaal_exbtwbedrag = ($exbtwbedrag - ($exbtwbedrag * ($_SESSION["aktie_korting"] / 100)));
                } else {
                    $Subtotaal_exbtwbedrag = $exbtwbedrag;
                }
                $btwbedrag = ($Subtotaal_exbtwbedrag * 0.19);
                $inbtwbedrag = ($Subtotaal_exbtwbedrag * 1.19);
                if (isset($_SESSION["cadeaubon_waarde"])) {

                    $Total = ($inbtwbedrag - $_SESSION["cadeaubon_waarde"]);
                } else {
                    $Total = $Subtotaal_exbtwbedrag + $btwbedrag;
                }

               // die("UPDATE offerte SET prijs_zonder_korting='$periode_subtotaal',  kortingprijs='$staffelkorting',  totaalprijs='$Total',   offertestatus='offerte',  cadeaubon_id=$cadeaubon_id, WHERE offerte_id=" . $offerte_id);

                $offerte_updte =  mysql_query("  UPDATE  `dbme_nl_servan`.`offerte` SET  `prijs_zonder_korting` =  '$periode_subtotaal',
                `kortingprijs` =  '$staffelkorting',
                `totaalprijs` =  '$Total',
                `offerte_datum` = NOW(),
                `cadeaubon_id` =  '$cadeaubon_id' WHERE  `offerte`.`offerte_id` =".$offerte_id." LIMIT 1 ");
                
                $offerte_updte_id = mysql_insert_id();

                if (isset($offerte_updte_id) && ($offerte_updte_id > 0 )) {

                    echo "DE OFFERTE MAILLEN NAAR DE KLANT EN NAAR SITE BEHEERDER";
                    //  2--- NAAR DE THANKS! PAGE GAAN.
                }
            }
        }
    }
    session_destroy();
}
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <title>dbme</title>
        <link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" title="no title" charset="utf-8" />
        <link rel="stylesheet" href="css/template.css" type="text/css" media="screen" title="no title" charset="utf-8" />
        <script src="js/jquery.js" type="text/javascript"></script>
        <script src="js/jquery.validationEngine-nl.js" type="text/javascript"></script>
        <script src="js/jquery.validationEngine.js" type="text/javascript"></script>
    </head>
   <body>
    <div>
        <form id="formID" class="formular" method="post" action="bestelling.php">
            <input type="hidden" name="action" value="multiple" />
            <input type="hidden" name="aantal_dag" value="<?php echo $aantal_dag; ?>" />
            <input type="hidden" name="van" value="<?php echo $_POST['van']; ?>" />
            <input type="hidden" name="tot" value="<?php echo $_POST['tot']; ?>" />
            <input type="hidden" name="dt" value="<?php echo $_POST['dt']; ?>" />
            <input type="hidden" name="cadeaubon" value="<?php echo $_POST['cadeaubon']; ?>" />
<?php
if (isset($_POST['set_id'])) {
    echo'<input type="hidden" name="set_id" value="' . $_POST['set_id'] . '" />';
}
if (isset($_POST['product'])) {
    foreach ($_POST["product"] as $product_id) {
        echo'<input type="hidden" name="product[]" value="' . $product_id . '" />';
    }
}
foreach ($_POST["aantal"] as $aantal) {
    echo'<input type="hidden" name="aantal[]" value="' . $aantal . '" /> ';
}
if (isset($_POST['dienst'])) {
    foreach ($_POST['dienst'] as $dienst_id) {
        echo'<input type="hidden" name="dienst[]" value="' . $dienst_id . '" />';
    }
}
?>


            <div>
                <fieldset>
                    <legend>klant</legend>
                    <p>bedrijfsnaam:<input type = "text"  class="validate[required.custom[onlyLetter],length[0,100]] text-input" name="bedrijfsnaam" id="bedrijfsnaam" /> </p>
                    <p>contactnaam:<input type = "text" class="validate[required.custom[onlyLetter],funcCall[validate2fields],length[0,100]] text-input" name="contactnaam" id="contactnaam" value=""  /> </p>
                    <p>straat/nr:<input type = "text"  class="validate[required] text-input" id="straat" name="straat" value="" /> </p>
                    <p>postcode:<input type = "text" class="validate[required] text-input" id="postcode" name="postcode" value="" placeholder="1200 AK" /> </p>
                    <p>plaats:<input type = "text"  class="validate[required.custom[onlyLetter],funcCall[validate2fields],length[0,100]] text-input" id="plaats" name="plaats" value="" /> </p>
                    <p>tel nr:<input type = "tel"  class="validate[required.custom[telephone]],length[10,100]] text-input" id="tel" name="tel" value="" /> </p>
                    <p>email:<input type = "email" class="validate[required.custom[email]] text-input" id="email" name="email" value=""  /> </p>
                    <p>email:<input type = "email" class="validate[required.confirm[email]] text-input" id="email2" /> </p>
                </fieldset>

            </div> 
            <div>
                <fieldset>
                    <legend>event loactie</legend>
                    <p>aanvangstijd:<input type = "time" class="validate[required] text-input" id="aanvangstijd" name="aanvangstijd" value=""  /> </p>
                    <p>naam:<input type = "text" class="validate[required.custom[onlyLetter],length[0,100]] text-input" id="contactnaam2" name="contactnaam2" value=""  /> </p>
                    <p>straat/nr:<input type = "text" class="validate[required] text-input" id="straat2" name="straat2" value="" /> </p>
                    <p>postcode:<input type = "text" class="validate[required] text-input"  id="postcode2" name="postcode2" value="" /> </p>
                    <p>plaats:<input type = "text"  class="validate[required.custom[onlyLetter],length[0,100]] text-input" id="plaats2" name="plaats2" value="" /> </p>
                    <p>tel nr:<input type = "tel"  class="validate[required.custom[telephone]],length[10,100]] text-input"  id="tel2" name="tel2" value="" /> </p>
                    <p>naam contactpersoon lokatie: <input type = "text" id="naam_cont_loc" name="naam_cont_loc" value="" /> </p>

                    <p><span>halen <input class="validate[required] radio" type="radio" name="hb"  id="radio1"  value="halen" /></span></p>
                    <p><span>brengen <input class="validate[required] radio" type="radio" name="hb"  id="radio2"  value=" brengen"/> </span></p>

                    <p>
                        <label for="agree">Please agree to our policy</label>
                        <input type="checkbox" class="validate[required] checkbox" id="agree" name="agree" />
                    </p>
                    <p>
                        <input class="submit" type="submit" value="Submit"/>
                    </p>
                </fieldset>

            </div>

        </form>
    </div>
</body>
</html>